package com.lyy.component;


import cn.hutool.core.util.StrUtil;
import com.lyy.annotation.SkipToken;
import com.lyy.result.Result;
import com.lyy.result.ResultCode;
import com.lyy.util.JwtUtil;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author Liangyaoyun
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @SneakyThrows
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) {

        // 若目标方法不是Controller方法，则直接放行
        if (!(handler instanceof HandlerMethod)){ return true;}

        // 若请求头中不存在token令牌，则抛出异常
        String token = req.getHeader("token");
        if (StrUtil.isBlank(token)) {throw new RuntimeException("拦截器: Token令牌失效");}

        // 解析token令牌
        Map<String, Object> verifyResult = JwtUtil.verify(token);

        // 若Token令牌即将过期，则返回新的Token令牌
        if ((boolean) verifyResult.get("expireSoon")) {
            String newToken = (String) verifyResult.get("newToken");
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().print(new Result(ResultCode.TOKEN_EXPIRING_SOON, newToken));
            return false;
        }

        // 将登录成功的用户主键存储在服务端Session会话中
        req.getSession().setAttribute("userId", verifyResult.get("userId"));

        // 放行
        return true;
    }
}

